<template>
    <div style="padding: 20px;">
        <el-row>
            <!--用户数据-->
            <el-col>
                <el-row>
                    <el-col :span="1.5">
                        <el-button type="warning" plain icon="Download" @click="handleExport"
                            v-hasPermi="['system:user:export']">导出</el-button>
                    </el-col>
                </el-row>
                <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">

                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column prop="index" width="50" label="序号" align="center">
                        <template #default="{$index}">
                            {{ $index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="学号" align="center" key="userId" prop="userId" width="250" />
                    <el-table-column label="学生名" align="center" key="studentName" prop="studentName" width="100"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="图书名" align="center" key="bookName" prop="bookName"
                        :show-overflow-tooltip="true" />
                    <el-table-column label="手机号" align="center" key="phone" prop="phone" width="120" />
                    <el-table-column label="状态" align="center" key="status">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)" disable-transitions>
                                {{ getStatusLabel(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createTime" 
                        width="160">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="width: 90%">
                    <div class="demo-pagination-block">
                        <el-pagination class="custom-pagination" v-model:current-page="pageNum"
                            v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]" :size="size" :background="true"
                            layout=" total,sizes, prev, pager, next" :total="total" @size-change="onPageSize"
                            @current-change="onPageChange" />
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup name="User">
    import {
        getToken
    } from "@/utils/auth";
    import {
        changeUserStatus,
        listUser,
        resetUserPwd,
        delUser,
        getUser,
        updateUser,
        addUser,
        deptTreeSelect
    } from "@/api/system/user";
    import useUserStore from '@/store/modules/user'
    import {
        getUserSchoolList,
        getAttendanceList,
        getReadBookList,
    } from "@/api/system/newuser";
    const userStore = useUserStore()
    const userInfo = userStore.id;
    const router = useRouter();
    const pageNum = ref(1);
    const total = ref(0);
    const pageSize = ref(15);
    const size = ref("default");
    const searchQuery = ref({
        id: userInfo,
        pageNum: pageNum.value,
        pageSize: pageSize.value,
    });
    const onPageChange = (num) => {
        pageNum.value = num;
        searchQuery.value.pageNum = num;
        getList();
    };

    const onPageSize = (num) => {
        pageSize.value = num;
        searchQuery.value.pageSize = num;
        getList();
    };


    const getStatusLabel = (status) => {
        switch (status) {
            case '0':
                return '已归还';
            case '1':
                return '正在阅读';
            case '2':
                return '逾期未归';
            default:
                return '未知';
        }
    };
    // 根据状态值返回对应的颜色类型
    const getStatusType = (status) => {
        switch (status) {
            case '0':
                return 'success'; 
            case '1':
                return 'primary'; 
            case '2':
                return 'warning'; 
            default:
                return '';
        }
    };



    const {
        proxy
    } = getCurrentInstance();
    const {
        sys_normal_disable,
        sys_user_sex
    } = proxy.useDict("sys_normal_disable", "sys_user_sex");
    const userList = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const title = ref("");
    const dateRange = ref([]);
    const deptName = ref("");
    const deptOptions = ref(undefined);
    const initPassword = ref(undefined);
    const postOptions = ref([]);
    const roleOptions = ref([]);
    /*** 用户导入参数 */
    const upload = reactive({
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
            Authorization: "Bearer " + getToken()
        },
        // 上传的地址
        url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
    });
    // 列显隐信息
    const columns = ref([{
            key: 0,
            label: `用户编号`,
            visible: true
        },
        {
            key: 1,
            label: `用户名称`,
            visible: true
        },
        {
            key: 2,
            label: `用户昵称`,
            visible: true
        },
        {
            key: 3,
            label: `部门`,
            visible: true
        },
        {
            key: 4,
            label: `手机号码`,
            visible: true
        },
        {
            key: 5,
            label: `状态`,
            visible: true
        },
        {
            key: 6,
            label: `创建时间`,
            visible: true
        }
    ]);

    const data = reactive({
        form: {},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            userName: undefined,
            phonenumber: undefined,
            status: undefined,
            deptId: undefined
        },
    });

    const {
        queryParams,
        form,
        rules
    } = toRefs(data);

    /** 通过条件过滤节点  */
    const filterNode = (value, data) => {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
    };

    /** 根据名称筛选部门树 */
    watch(deptName, val => {
        proxy.$refs["deptTreeRef"].filter(val);
    });

    /** 查询部门下拉树结构 */
    function getDeptTree() {
        deptTreeSelect().then(response => {
            deptOptions.value = response.data;
        });
    };
    /** 查询用户列表 */
    function getList() {
        loading.value = true;
        getReadBookList(searchQuery.value).then(res => {
            loading.value = false;
            userList.value = res.rows.map(row => ({
                ...row,
                status: row.status.toString()
            }));
            total.value = res.total;
        });
    };

    /** 节点单击事件 */
    function handleNodeClick(data) {
        queryParams.value.deptId = data.id;
        handleQuery();
    };


    /** 导出按钮操作 */
    function handleExport() {
        proxy.download("system/user/export", {
            ...queryParams.value,
        }, `user_${new Date().getTime()}.xlsx`);
    };


    /** 更多操作 */
    function handleCommand(command, row) {
        switch (command) {
            case "handleResetPwd":
                handleResetPwd(row);
                break;
            case "handleAuthRole":
                handleAuthRole(row);
                break;
            default:
                break;
        }
    };




    /** 选择条数  */
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.userId);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    };






    /** 提交上传文件 */
    function submitFileForm() {
        proxy.$refs["uploadRef"].submit();
    };

    /** 重置操作表单 */
    function reset() {
        form.value = {
            userId: undefined,
            deptId: undefined,
            userName: undefined,
            nickName: undefined,
            password: undefined,
            phonenumber: undefined,
            email: undefined,
            sex: undefined,
            status: "0",
            remark: undefined,
            postIds: [],
            roleIds: []
        };
        proxy.resetForm("userRef");
    };

    /** 取消按钮 */
    function cancel() {
        open.value = false;
        reset();
    };

    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        getUser().then(response => {
            postOptions.value = response.posts;
            roleOptions.value = response.roles;
            open.value = true;
            title.value = "添加用户";
            form.value.password = initPassword.value;
        });
    };

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const userId = row.userId || ids.value;
        getUser(userId).then(response => {
            form.value = response.data;
            postOptions.value = response.posts;
            roleOptions.value = response.roles;
            form.value.postIds = response.postIds;
            form.value.roleIds = response.roleIds;
            open.value = true;
            title.value = "修改用户";
            form.password = "";
        });
    };

    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["userRef"].validate(valid => {
            if (valid) {
                if (form.value.userId != undefined) {
                    updateUser(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    });
                } else {
                    addUser(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getList();
                    });
                }
            }
        });
    };

    getDeptTree();
    getList();
</script>
<style scoped>
    .demo-pagination-block {
        margin-top: 20px;
        text-align: left;
        display: block;
    }

    /* prev, pager, next */
    .custom-pagination .el-pagination__total {
        color: #000000;
    }
</style>